package servlet;

import pojo.*;
import pojo.cat.GoodsCat;
import pojo.cat.ShowGood;
import service.Impl.TgoodsServiceImpl;
import service.Impl.TorderServiceImpl;
import service.Impl.TuserAddressServiceImpl;
import service.TgoodsService;
import service.TorderService;
import service.TuserAddressService;
import util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

@MultipartConfig
@WebServlet("/goods/*")
public class TgoodsServlet extends HttpServlet {
    TgoodsService tgs = new TgoodsServiceImpl();
    TuserAddressService tds = new TuserAddressServiceImpl();
    TorderService to = new TorderServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取路径
        String rURI = request.getRequestURI();
        //拆分字符串截取路径
        String[] split = rURI.split("/");
        String ss = split[split.length - 1];
        //细分
        String[] split1 = ss.split("\\?");
        String s = split1[0];
        if ("queryGoodsList".equals(s)) {
            this.queryGoodsList(request, response);
        } else if ("selById".equals(s)) {
            this.selById(request, response);
        } else if ("addCat".equals(s)) {
            this.addCat(request, response);
        } else if ("selall".equals(s)) {
            this.selall(request, response);
        } else if ("delById".equals(s)) {
            this.delById(request, response);
        } else if ("addGood".equals(s)) {
            this.addGood(request, response);
        }
    }

    private void addGood(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        PrintWriter writer = response.getWriter();
        String id = request.getParameter("classifyLevel1Id");
        System.out.println(id);
        int id1 = Integer.parseInt(id);
        int id2 = Integer.parseInt(request.getParameter("classifyLevel2Id"));
        int id3 = Integer.parseInt(request.getParameter("classifyLevel3Id"));
        String goodsName = request.getParameter("goodsName");
        double price = Double.parseDouble(request.getParameter("price"));
        int stock = Integer.parseInt(request.getParameter("stock"));
        String goodsDesc = request.getParameter("goodsDesc");

        Part photo = request.getPart("photo");
        //获取要上传的文件路径
        String realPath = request.getSession().getServletContext().getRealPath("files/");

        //提取文件名
        String fileName = photo.getSubmittedFileName();

        //写入图片
        photo.write(realPath + fileName);

        Tgoods tgoods = new Tgoods(0, goodsName, goodsDesc, price, stock, id1, id2, id3, fileName, 0);

        int i = tgs.addGood(tgoods);

        if (i>0) {
            writer.print("<script>\n" +
                    "    location.href = \"/goodsList.jsp\";\n" +
                    "    alert(\"添加成功!\");\n" +
                    "</script>");
        } else {
            writer.print("<script>\n" +
                    "    location.href = \"/login.jsp\";\n" +
                    "    alert(\"添加失败!\");\n" +
                    "</script>");
        }

    }

    private void delById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int i = tgs.delById(Integer.parseInt(id));
        if (i > 0) {
            response.getWriter().print("true");
        }
    }

    private void selall(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Tgoods> getall = tgs.getall();
        request.setAttribute("getall", getall);
        request.getRequestDispatcher("/goodsList.jsp").forward(request, response);
    }

    private void addCat(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String opr = request.getParameter("opr");
        HttpSession session = request.getSession();
        PrintWriter writer = response.getWriter();
        GoodsCat cat = null;
        if ("add".equals(opr)) {
            String num = request.getParameter("num");
            String id = request.getParameter("id");
            if (session.getAttribute("cat") == null) {
                cat = new GoodsCat();
            } else {
                cat = (GoodsCat) session.getAttribute("cat");
            }
            Tgoods tgoods = tgs.selById(id);
            ShowGood sg = new ShowGood();
            sg.setTgoods(tgoods);
            sg.setNum(Integer.parseInt(num));
            String s = cat.addGoodCat(sg);
            cat.js();
            session.setAttribute("cat", cat);
            writer.print(s);
        }

        if ("show".equals(opr)) {
            request.getRequestDispatcher("/common/client/searchBar.jsp").forward(request, response);
        }

        if ("set1".equals(opr)) {
            request.getRequestDispatcher("/settlement1.jsp").forward(request, response);
        }

        if ("set2".equals(opr)) {
            Tuser user = (Tuser) session.getAttribute("user");
            List<TuserAddress> list = tds.selById(user.getId());
            request.setAttribute("list", list);
            request.getRequestDispatcher("/settlement2.jsp").forward(request, response);
        }

        if ("set3".equals(opr)) {
            //uuid生成随机字符串
            UUID uuid = UUID.randomUUID();
            String s = uuid.toString().toUpperCase();
            String[] split = s.split("-");
            String uu = "";
            for (String s1 : split) {
                uu += s1;
            }
            //获得选中地址
            String address = request.getParameter("address");
            //获取session中的购物车对象和用户对象
            Tuser user = (Tuser) session.getAttribute("user");
            cat = (GoodsCat) session.getAttribute("cat");
            //生成订单对象 返回自增主键
            Tbaseorder tb = new Tbaseorder(0, user.getId(), user.getAccount(), address, null, cat.getSum(), uu);
            int i = to.addTbase(tb);
            String oid = String.valueOf(i);
            if (i > 0) {
                //生成订单详情
                for (ShowGood showGood : cat.getGoodlist()) {
                    to.addTbinfo(new Torderinfo(0, oid, showGood.getTgoods().getId(), showGood.getNum(), showGood.getPrice()));
                }
            }
            request.setAttribute("uuid", uu);
            request.setAttribute("address", address);
            request.setAttribute("catSum", cat.getSum());
            request.getSession().removeAttribute("cat");
            request.getRequestDispatcher("/settlement3.jsp").forward(request, response);
        }

    }

    private void selById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Tgoods tgoods = tgs.selById(id);
        request.setAttribute("good", tgoods);
        request.getRequestDispatcher("/goodsDetail.jsp").forward(request, response);
    }


    private void queryGoodsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int ids = 0;
        if (id != null && !"".equals(id)) {
            ids = Integer.parseInt(id);
        }
        String name = request.getParameter("keyWord");

        String dqys = request.getParameter("pageNo");
        int pageNo = dqys == null ? 1 : Integer.parseInt(dqys);

        Page page = tgs.selgoods(ids, name, pageNo);

        request.setAttribute("page", page);
        request.setAttribute("keyWord", name);
        request.setAttribute("id", id);
        request.getRequestDispatcher("/queryGoodsList.jsp").forward(request, response);
    }
}
